﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WaterRevenueMS.WebUI.Common;
using System.ComponentModel.Composition;
using WaterRevenueMS.Core.Service.Customer;
using WaterRevenueMS.Core.Service.BasicSet;
using WaterRevenueMS.WebUI.Extension.Filters;
using WaterRevenueMS.Domain.Common.Models;
using WaterRevenueMS.Domain.ViewModels.Maintenance.MeterInfoRepair;
using WaterRevenueMS.Domain.ViewModels.BasicSet.KindOfWaterUse;
using WaterRevenueMS.Domain.ViewModels.BasicSet.RelayType;
using WaterRevenueMS.Domain.ViewModels.BasicSet.ConcentratorType;
using WaterRevenueMS.Domain.ViewModels.BasicSet.HandSetType;
using WaterRevenueMS.Componnent.Common;
using System.Linq.Expressions;
using WaterRevenueMS.Componnent.Entities.Customer;
using WaterRevenueMS.WebUI.Extension.MvcHelper;
using WaterRevenueMS.Domain.ViewModels.BasicSet.WayOfCharge;
using WaterRevenueMS.Domain.ViewModels.BasicSet.MeterType;
using WaterRevenueMS.Domain.ViewModels.BasicSet.WaterCaliber;
using WaterRevenueMS.Domain.ViewModels.BasicSet.Manufacturer;
using WaterRevenueMS.Domain.ViewModels.Maintenance.RepairRecord;
using WaterRevenueMS.Core.Service.Maintenance;
namespace WaterRevenueMS.WebUI.Controllers
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class MeterRepairController : AdminController
    {
        [Import]
        public IMeterInfoService MeterInfoService { get; set; }

        [Import]
        private ICustomerService CustomerService { get; set; }

        [Import]
        private IWayOfChargeService WayOfChargeService { get; set; }

        [Import]
        private IKindOfWaterUseService KindOfWaterUserService { get; set; }

        [Import]
        private IMeterTypeService MeterTypeService { get; set; }

        [Import]
        private IRelayTypeService RelayTypeService { get; set; }

        [Import]
        private IConcentratorTypeService ConcentratorTypeService { get; set; }

        [Import]
        private IHandSetTypeService HandSetTypeService { get; set; }

        [Import]
        private IWaterCaliberService WaterCaliberService { get; set; }

        [Import]
        private IManufacturerService ManufacturerService { get; set; }

        [Import]
        private IRepairRecordService RepairRecordService { get; set; }

        [AdminLayout]
        public ActionResult Index()
        {
            var model = new MeterInfoRepairModel();
            var KindOfWaterUseDatas = KindOfWaterUserService.KindOfWaterUses.Where(t => t.IsDeleted == false)
                .Select(t => new KindOfWaterUseModel
                {
                    Id = t.Id,
                    Yong_SXZ = t.Yong_SXZ
                });
            foreach (var item in KindOfWaterUseDatas)
            {
                model.Search.KindOfWaterUseItems.Add(new SelectListItem { Text = item.Yong_SXZ, Value = item.Id.ToString() });
            }
            var RelayTypeDatas = RelayTypeService.RelayTypes.Where(t => t.IsDeleted == false)
                .Select(t => new RelayTypeModel
                {
                    Id = t.Id,
                    Zhong_JLX = t.Zhong_JLX
                });
            foreach (var item in RelayTypeDatas)
            {
                model.Search.RelayTypeItems.Add(new SelectListItem { Text = item.Zhong_JLX, Value = item.Id.ToString() });
            }
            var ConcentratorTypeDatas = ConcentratorTypeService.ConcentratorTypes.Where(t => t.IsDeleted == false)
                .Select(t => new ConcentratorTypeModel
                {
                    Id = t.Id,
                    Ji_ZQLX = t.Ji_ZQLX
                });
            foreach (var item in ConcentratorTypeDatas)
            {
                model.Search.ConcentratorTypeItems.Add(new SelectListItem { Text = item.Ji_ZQLX, Value = item.Id.ToString() });
            }
            var HandSetDatas = HandSetTypeService.HandSetTypes.Where(t => t.IsDeleted == false)
                .Select(t => new HandSetTypeModel
                {
                    Id = t.Id,
                    Shou_CQLX = t.Shou_CQLX
                });
            foreach (var item in HandSetDatas)
            {
                model.Search.HandSetItems.Add(new SelectListItem { Text = item.Shou_CQLX, Value = item.Id.ToString() });
            }
            return View(model);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult List(DataTableParameter param)
        {
            int total = MeterInfoService.MeterInfos.Count(t => t.IsDeleted == false);

            var expr = BuildSearchCriteria();

            var filterResult = MeterInfoService.MeterInfos.Where(expr).Select(t => new MeterInfoRepairModel
            {
                Id = t.Id,
                CustomerName = t.Customer != null ? t.Customer.Hu_ZXM : "",
                WayOfChargeName = t.WayOfCharge != null ? t.WayOfCharge.Shou_FFS : "",
                KindOfWaterUseName = t.KindOfWaterUse != null ? t.KindOfWaterUse.Yong_SXZ : "",
                MeterTypeName = t.MeterType != null ? t.MeterType.Yi_BLX : "",
                RelayTypeName = t.RelayType != null ? t.RelayType.Zhong_JLX : "",
                Zhong_JDZ = t.Zhong_JDZ,
                Zhong_JTD = t.Zhong_JTD,
                ConcentratorTypeName = t.ConcentratorType != null ? t.ConcentratorType.Ji_ZQLX : "",
                Ji_ZQDZ = t.Ji_ZQDZ,
                Ji_ZQTD = t.Ji_ZQTD,
                HandSetName = t.HandSetType != null ? t.HandSetType.Shou_CQLX : "",
                WaterCaliberName = t.WaterCaliber != null ? t.WaterCaliber.Shui_BKJ : "",
                Yi_BMC = t.Yi_BMC,
                Yi_BBH = t.Yi_BBH,
                Yi_BDZ = t.Yi_BDZ,
                Yi_BDD = t.Yi_BDD,
                Du_SBQ = t.Du_SBQ,
                Chao_BDTBC = t.Chao_BDTBC,
                Chao_BDTSC = t.Chao_BDTSC,
                Du_SSQ = t.Du_SSQ,
                Du_SBC = t.Du_SBC,
                OrderNo = t.OrderNo,


            }).OrderBy(t => t.OrderNo).Skip(param.iDisplayStart).Take(param.iDisplayLength).ToList();

            int sortId = param.iDisplayStart + 1;

            var result = from c in filterResult
                         select new[]
                        {
                            c.Id.ToString(),
                            sortId++.ToString(), 
                            c.Yi_BBH,
                            c.Yi_BDZ,
                            c.Du_SBQ.ToString(),
                            c.Chao_BDTBC.ToString(),
                            c.Du_SSQ.ToString(),
                            c.Chao_BDTSC.ToString(),
                            c.Du_SBC.ToString(),
                            c.Id.ToString()
                        };

            return Json(new
            {
                sEcho = param.sEcho,
                iDisplayStart = param.iDisplayStart,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Edit(int Id)
        {
            var model = new RepairRecordModel();
            model.Meter_No = Id;
            model.CreateDT = DateTime.Now; ;
            var modell = new MeterInfoRepairModel();

            var entity = MeterInfoService.MeterInfos.FirstOrDefault(t => t.Id == Id);
            if (null != entity)
            {
                model.Yi_BDZ = entity.Yi_BDZ;

            }
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Edit(RepairRecordModel model)
        {
            RepairRecordService.GetLiuSModel(model);

            RepairRecordService.ChangeState(model);
            if (ModelState.IsValid)
            {

                OperationResult result = (RepairRecordService.Insert(model));
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }

            }
            else
            {
                return PartialView(model);
            }
        }
        [AdminPermission(PermissionCustomMode.Ignore)]
        public string GenerateRepair(string idList)
        {
            string strJson = "{\"state\":\"";
            strJson = strJson + "1\",\"message\":\"成功\"}";
            string[] idL = idList.Split(',');



   //         String str = "1002, 1003, 1004, 1005, 100645";
     //       String[] strs = str.Split(',');
       //     
         //   for (Int32 i = 0; i < strs.Length; i++)
           // {
             //   arrInt[i] = Int32.Parse(strs[i].Trim());
            //}


            var model = new RepairRecordModel();
            for (Int32 i = 0; i < idL.Length; i++)
            {
                if (idL[i].Trim() != "")
                {
                    Int32 id = Int32.Parse(idL[i].Trim());
                    if ((id != 0))
                    {
                        model.Meter_No = id;

                        RepairRecordService.GetLiuSModel(model);
                        RepairRecordService.Insert(model);
                    }
                }

            }

           

            return strJson;
        }

        //Update
        private Expression<Func<MeterInfo, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<MeterInfo> bulider = new DynamicLambda<MeterInfo>();
            Expression<Func<MeterInfo, Boolean>> expr = null;
            if (!string.IsNullOrEmpty(Request["Yi_BBH"]))
            {
                var data = Request["Yi_BBH"].Trim();
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Yi_BBH.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Yi_BMC"]))
            {
                var data = Request["Yi_BMC"].Trim();
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Yi_BMC.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Zhong_JDZ"]))
            {
                var data = Request["Zhong_JDZ"].Trim();
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Zhong_JDZ.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Ji_ZQDZ"]))
            {
                var data = Request["Ji_ZQDZ"].Trim();
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Ji_ZQDZ.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Yong_SLX_No"]))
            {
                var data = Convert.ToInt32(Request["Yong_SLX_No"]);
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Yong_SLX_No == data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Zhong_JLX_No"]))
            {
                var data = Convert.ToInt32(Request["Zhong_JLX_No"]);
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Zhong_JLX_No == data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Shou_CQLX_No"]))
            {
                var data = Convert.ToInt32(Request["Shou_CQLX_No"]);
                Expression<Func<MeterInfo, Boolean>> tmp = t => t.Shou_CQLX_No == data;
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Ji_ZQLX_No"]) && Request["Ji_ZQLX_No"] != "0")
            {
                var data = Convert.ToInt32(Request["Ji_ZQLX_No"]);
                Expression<Func<MeterInfo, Boolean>> tmp = t => (t.Ji_ZQLX_No == data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            Expression<Func<MeterInfo, Boolean>> tmpSolid = t => t.IsDeleted == false;
            expr = bulider.BuildQueryAnd(expr, tmpSolid);

            return expr;
        }

        private void InitModuleSet(MeterInfoRepairModel model)
        {
            //客户
            //收费方式
            var WayOfChargeDatas = WayOfChargeService.WayOfCharges.Where(t => t.IsDeleted == false)
                .Select(t => new WayOfChargeModel
                {
                    Id = t.Id,
                    Shou_FFS = t.Shou_FFS
                });
            foreach (var item in WayOfChargeDatas)
            {
                model.WayOfChargeItems.Add(new SelectListItem { Text = item.Shou_FFS, Value = item.Id.ToString() });
            }
            //用水类型
            var KindOfWaterUseDatas = KindOfWaterUserService.KindOfWaterUses.Where(t => t.IsDeleted == false)
                .Select(t => new KindOfWaterUseModel
                {
                    Id = t.Id,
                    Yong_SXZ = t.Yong_SXZ
                });
            foreach (var item in KindOfWaterUseDatas)
            {
                model.KindOfWaterUseItems.Add(new SelectListItem { Text = item.Yong_SXZ, Value = item.ToString() });
            }
            //仪表类型
            var MeterTypeDatas = MeterTypeService.MeterTypes.Where(t => t.IsDeleted == false)
                .Select(t => new MeterTypeModel
                {
                    Id = t.Id,
                    Yi_BLX = t.Yi_BLX
                });
            foreach (var item in MeterTypeDatas)
            {
                model.MeterTypeItems.Add(new SelectListItem { Text = item.Yi_BLX, Value = item.Id.ToString() });
            }
            //中继类型
            var RelayTypeDatas = RelayTypeService.RelayTypes.Where(t => t.IsDeleted == false)
                .Select(t => new RelayTypeModel
                {
                    Id = t.Id,
                    Zhong_JLX = t.Zhong_JLX
                });
            foreach (var item in RelayTypeDatas)
            {
                model.RelayTypeItems.Add(new SelectListItem { Text = item.Zhong_JLX, Value = item.Id.ToString() });
            }
            //集中器类型
            var ConcentratorTypeDatas = ConcentratorTypeService.ConcentratorTypes.Where(t => t.IsDeleted == false)
                .Select(t => new ConcentratorTypeModel
                {
                    Id = t.Id,
                    Ji_ZQLX = t.Ji_ZQLX
                });
            foreach (var item in ConcentratorTypeDatas)
            {
                model.ConcentratorTypeItems.Add(new SelectListItem { Text = item.Ji_ZQLX, Value = item.Id.ToString() });
            }
            //手抄器类型
            var HandSetDatas = HandSetTypeService.HandSetTypes.Where(t => t.IsDeleted == false)
                .Select(t => new HandSetTypeModel
                {
                    Id = t.Id,
                    Shou_CQLX = t.Shou_CQLX
                });
            foreach (var item in HandSetDatas)
            {
                model.HandSetItems.Add(new SelectListItem { Text = item.Shou_CQLX, Value = item.Id.ToString() });
            }
            //水表口径
            var WatercaliberDatas = WaterCaliberService.WaterCalibers.Where(t => t.IsDeleted == false)
                .Select(t => new WaterCaliberModel
                {
                    Id = t.Id,
                    Shui_BKJ = t.Shui_BKJ
                });
            foreach (var item in WatercaliberDatas)
            {
                model.WaterCaliberItems.Add(new SelectListItem { Text = item.Shui_BKJ, Value = item.Id.ToString() });
            }
            //水表厂商
            var ManufacturerDatas = ManufacturerService.Manufacturers.Where(t => t.IsDeleted == false)
                .Select(t => new ManufacturerModel
                {
                    Id = t.Id,
                    Shui_BCS = t.Shui_BCS
                });
            foreach (var item in ManufacturerDatas)
            {
                model.ManufacturerItems.Add(new SelectListItem { Text = item.Shui_BCS, Value = item.Id.ToString() });
            }
        }

    }
}

